import * as turf from '@turf/turf'

// MeasurePolygon
/*
绘制面
 */
class MeasurePolygon {
  constructor(arg) {
    this.viewer = arg.viewer
    this.Cesium = arg.Cesium
    this.callback = arg.callback
    this._polygon = null //活动面
    this._polygonLast = null //最后一个面

    this._positions = [] //活动点
    this._tmppositions = []//临时活动点

    this._entities_point = [] //脏数据
    this._entities_polygon = [] //脏数据
    this._polygonData = null //用户构造面
  }

  //返回最后活动面
  get polygon() {
    return this._polygonLast
  }

  //返回面数据用于加载面
  getData() {
    return this._polygonData
  }

  //加载面
  loadPolygon(data, option) {
    var $this = this
    /* return this.viewer.entities.add({
      polygon: {
        hierarchy: new $this.Cesium.PolygonHierarchy(data),
        clampToGround: true,
        show: true,
        fill: option.flag,
        material: $this.Cesium.Color.fromCssColorString(option.color),
        width: 3,
        outlineColor: $this.Cesium.Color.fromCssColorString(option.outLineColor),
        outlineWidth: 10,
        outline: !option.flag
      }
    }) */
    var polygon = ""
    polygon = this.viewer.dataSourceDisplay._defaultDataSource.entities.add({
      polygon: {
        hierarchy: new $this.Cesium.PolygonHierarchy(data),
        clampToGround: true,
        show: true,
        fill: option.flag,
        material: $this.Cesium.Color.fromCssColorString(option.color),
        width: 20,
        outlineColor: $this.Cesium.Color.fromCssColorString(option.outLineColor),
        outlineWidth: 30,
        outline: !option.flag
      }
    })
    // if (option.flah) {
    //   polygon = this.viewer.dataSourceDisplay._defaultDataSource.entities.add({
    //     polygon: {
    //       hierarchy: new $this.Cesium.PolygonHierarchy(data),
    //       clampToGround: true,
    //       show: true,
    //       fill: option.flag,
    //       material: $this.Cesium.Color.fromCssColorString(option.color),
    //       width: 20,
    //       outlineColor: $this.Cesium.Color.fromCssColorString(option.outLineColor),
    //       outlineWidth: 30,
    //       outline: !option.flag
    //     }
    //   })
    // } else {
    //   data.push(data[0])
    //   polygon = this.viewer.dataSourceDisplay._defaultDataSource.entities.add({
    //     polyline: {
    //       position: new $this.Cesium.CallbackProperty(function () {
    //         return data
    //       }, false),
    //       show: true,
    //       material: $this.Cesium.Color.fromCssColorString(option.outLineColor),
    //       width: 5,
    //       clampToGround: true
    //     }
    //   })
    // }
    return polygon;
  }

  //开始绘制
  startCreate(option) {
    var $this = this
    this.handler = new this.Cesium.ScreenSpaceEventHandler(this.viewer.cesiumViewer.scene.canvas)
    this.handler.setInputAction(function (evt) { //单机开始绘制
      var cartesian = $this.getCatesian3FromPX(evt.position)
      if (!cartesian) return
      if ($this._positions.length == 0) {
        $this._positions.push(cartesian.clone())

        
      }
      $this.createPoint(cartesian)
      $this._positions.push(cartesian)
    }, $this.Cesium.ScreenSpaceEventType.LEFT_CLICK)
    this.handler.setInputAction(function (evt) { //移动时绘制面
      if ($this._positions.length < 1) return
      var cartesian = $this.getCatesian3FromPX(evt.endPosition)
      if (!cartesian) return
      if ($this._positions.length == 3) {
        if (!$this.Cesium.defined($this._polygon)) {

          $this._polygon = $this.createPolygon(option)
        }
      }
      $this._positions.pop()
      $this._positions.push(cartesian)

    }, $this.Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    this.handler.setInputAction(function (evt) {
      if (!$this._polygon) return
      var cartesian = $this.getCatesian3FromPX(evt.position)
      if (!cartesian) return
      $this._positions.pop()
      $this._positions.push(cartesian)

      $this._tmppositions = [...$this._positions]
     
      $this.createPoint(cartesian)
      $this._polygonData = $this._positions.concat()
      $this.viewer.dataSourceDisplay._defaultDataSource.entities.remove($this._positions) //移除
      $this._positions = null
      $this._positions = []
      var Polygon = $this.loadPolygon($this._polygonData, option)
      $this._entities_polygon.push(Polygon)

      console.log($this._tmppositions)
      var area = $this.getArea($this._tmppositions)

      $this._polygonLast = Polygon
      if (typeof $this.callback == 'function') {
        $this.callback( `${area.toFixed(2)}平方米`)
      }
      $this.clearPoint()
      $this.destroy()
    }, $this.Cesium.ScreenSpaceEventType.RIGHT_CLICK)
  }

  //创建面
  createPolygon(option) {
    var $this = this
    var polygon = this.viewer.dataSourceDisplay._defaultDataSource.entities.add({
      polygon: {
        hierarchy: new $this.Cesium.CallbackProperty(function () {
          return new $this.Cesium.PolygonHierarchy($this._positions)
        }, false),
        clampToGround: true,
        show: true,
        fill: option.flag,
        material: $this.Cesium.Color.fromCssColorString(option.color),
        width: 3,
        outlineColor: $this.Cesium.Color.fromCssColorString(option.outLineColor),
        outlineWidth: 10,
        outline: !option.flag
      }
    })
    $this._entities_polygon.push(polygon)
    return polygon
  }

  //创建点
  createPoint(cartesian) {
    var $this = this
    var point = this.viewer.dataSourceDisplay._defaultDataSource.entities.add({
      position: cartesian,
      point: {
        pixelSize: 10,
        color: $this.Cesium.Color.YELLOW
      }
    })
    $this._entities_point.push(point)
    return point
  }


  clearPoint() {
    for (var i = 0; i < this._entities_point.length; i++) {
      this.viewer.dataSourceDisplay._defaultDataSource.entities.remove(this._entities_point[i])
    }
    this._entities_point = [] //脏数据
  }

  //销毁事件
  destroy() {
    if (this.handler) {
      this.handler.destroy()
      this.handler = null
    }
  }

  //清空实体对象
  clear() {
    for (var i = 0; i < this._entities_point.length; i++) {
      this.viewer.dataSourceDisplay._defaultDataSource.entities.remove(this._entities_point[i])
    }
    for (var i = 0; i < this._entities_polygon.length; i++) {
      this.viewer.dataSourceDisplay._defaultDataSource.entities.remove(this._entities_polygon[i])
    }
    this._polygon = null //活动面
    this._polygonLast = null //最后一个面
    this._positions = [] //活动点
    this._entities_point = [] //脏数据
    this._entities_polygon = [] //脏数据
    this._polygonData = null //用户构造面
  }

  getCatesian3FromPX(px) {
    var cartesian
    var ray = this.viewer.cesiumViewer.camera.getPickRay(px)
    if (!ray) return null
    cartesian = this.viewer.cesiumViewer.scene.globe.pick(ray, this.viewer.cesiumViewer.scene)
    if (!cartesian) {
      cartesian = this.viewer.cesiumViewer.camera.pickEllipsoid(px, this.viewer.cesiumViewer.scene.globe.ellipsoid)
    }
    return cartesian
  }







  //计算曲面面积
  getArea(points){
    // //拆分三角曲面

    // var res = 0;

    // for (let i = 0; i < points.length - 2; i++) {
    //   var j = (i + 1)% points.length;
    //   var k = (i + 2)% points.length;
    //   var totalAngle = this.angle(points[i], points[j], points[k]);

    //   var dis_temp1 = this.distance(points[i], points[j])
    //   var dis_temp2 = this.distance(points[j], points[k])

    //   //面积公式 a*b*sin(C)/2
    //   res += dis_temp1*dis_temp2*Math.abs(Math.sin(totalAngle))
    //   console.log(res)


      
    // }
    
    var positions = [[]]
    for (let i = 0; i < points.length; i++) {
      var point = this.Cesium.Cartographic.fromCartesian(points[i])
      positions[0].push([this.Cesium.Math.toDegrees(point.latitude), this.Cesium.Math.toDegrees(point.longitude)])
    }
    var point = this.Cesium.Cartographic.fromCartesian(points[0])
    positions[0].push([this.Cesium.Math.toDegrees(point.latitude), this.Cesium.Math.toDegrees(point.longitude)])
    console.log(positions)
    var polygon = turf.polygon(positions)
    var area = turf.area(polygon)
    // console.log(area)
    return area
  }
  
  // angle(p1, p2, p3){
  //   var p1t = this.Cesium.Cartographic.fromCartesian( p1)
  //   var p2t = this.Cesium.Cartographic.fromCartesian( p2)
  //   var p3t = this.Cesium.Cartographic.fromCartesian( p3)
  //   p1t.height = 0.0;
  //   p2t.height = 0.0;
  //   p3t.height = 0.0;
  //   var bearing21 = this.bearing(p2t, p1t);
  //   var bearing23 = this.bearing(p2t, p3t);
  //   var angle = bearing23 - bearing21;
  //   if(angle <0){
  //     angle +=360;
  //   }
  //   return angle;
  // }
  
  // bearing(from, to){
  //   var radiansPerDegree = Math.PI/180.0;//角度转弧度
  //   var degreesPerRadian = Math.PI/180.0;//弧度转角度


  //   var lat1 = from.latitude*radiansPerDegree;
  //   var lon1 = from.longitude*radiansPerDegree;
  //   var lat2 = to.latitude*radiansPerDegree;
  //   var lon2 = to.longitude*radiansPerDegree;

  //   var angle = -Math.atan2(
  //     Math.sin(lon1-lon2) * Math.cos(lat2),
  //     Math.cos(lat1)*Math.sin(lat2) - Math.sin(lat1)*Math.cos(lat2)*Math.cos(lon1 - lon2)
  //     )
  //   if(angle < 0){
  //     angle += Math.PI*2.0;
  //   }

  //   angle = angle* degreesPerRadian;

  //   return angle;

  // }
  // //平面距离
  // distance(point1, point2){
  //   var p1 = this.Cesium.Cartographic.fromCartesian( point1)
  //   p1.height = 0.0;
  //   var p2 = this.Cesium.Cartographic.fromCartesian(point2)
  //   p2.height = 0.0;
  //   var geoD = new this.Cesium.EllipsoidGeodesic();
  //   geoD.setEndPoints(p1, p2)
  //   var innerS = geoD.surfaceDistance;
  //   return innerS
  // }
}


export default MeasurePolygon
